package com.example.yuanqispringbootshiro.utils;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;


public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        /**
         * 假数据
         * 此处应该查询数据库中的权限
         */
        Set<String> permissionSet = new HashSet<String>();
        permissionSet.add("权限1");
        permissionSet.add("权限2");
        info.setStringPermissions(permissionSet);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)authenticationToken;

        String username = usernamePasswordToken.getUsername();

        /**
         * 这里用假数据验证用户
         * 本应该连接数据库查询
         */
        if (username == null){
            return null;
        }

        /**
         * 用假数据代替查询到的用户密码
         */
        String password = "123";

        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
